package com.ukao.steward.ui.menuLeft.myEarnings;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.BlankTableBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.PickerViewDialog;
import com.ukao.steward.listener.MyTextWatcher;
import com.ukao.steward.pesenter.valetRunners.FillBlankPesenter;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.CountDownUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.RegularUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.FillBlankView;
import com.ukao.steward.widget.ClearEditText;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.accountName_layout;

/**
 * 填写银卡卡信息
 */
public class FillBlankFragment extends MvpFragment<FillBlankPesenter>  implements FillBlankView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static boolean shouldStopChange;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    Unbinder unbinder;
    @BindView(R.id.accountName)
    TextView accountName;
    @BindView(R.id.product_name)
    ClearEditText name;
    @BindView(R.id.accountNo)
    ClearEditText accountNo;
    @BindView(R.id.phone)
    ClearEditText phone;
    @BindView(R.id.code)
    ClearEditText code;
    @BindView(R.id.btn_verify)
    TextView btnVerify;
    @BindView(R.id.next_btn)
    Button nextBtn;
    @BindView(accountName_layout)
    LinearLayout accountNameLayout;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private CountDownUtils mCountDownUtils;
    private String strphone;
    private String strname;
    private String straccountName;
    private String strcode;
    private String straccountNo;
    private OptionsPickerView mBalankDialog;
    private List<BlankTableBean> mBlankTableBean;
    public String bankCode="";

    public static FillBlankFragment newInstance(String param1, String param2) {
        FillBlankFragment fragment = new FillBlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected FillBlankPesenter createPresenter() {
        return new FillBlankPesenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_fill_blank, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        mCountDownUtils = new CountDownUtils(btnVerify, "获取验证码", 60, 1);
        title.setText("添加银行卡");
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
    }


    @Override
    protected void initListener() {
        super.initListener();

        phone.addTextChangedListener(mTextWatcher);
        name.addTextChangedListener(mTextWatcher);
        accountName.addTextChangedListener(mTextWatcher);
        code.addTextChangedListener(mTextWatcher);
        btnVerify.addTextChangedListener(mTextWatcher);
        accountNo.addTextChangedListener(mMyTextWatcher);
        code.setOnEditorActionListener(mOnEditorActionListener);
    }

    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            L.i("event=" + event + "actionId=" + actionId);
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
                if (nextBtn.isEnabled()) {
                    addBank();
                }

            }

            return false;
        }
    };


    public String getBankCardText() {
        return accountNo.getText().toString().trim().replaceAll(" ", "");
    }


    private MyTextWatcher mMyTextWatcher = new MyTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            format(s, accountNo);
            isILoginGo();
        }
    };


    private MyTextWatcher mTextWatcher = new MyTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            isILoginGo();
        }
    };


    public static final String space = " ";

    public static void format(Editable editable, EditText bandCardEdit) {
        if (shouldStopChange) {
            shouldStopChange = false;
            return;
        }

        shouldStopChange = true;

        String str = editable.toString().trim().replaceAll(space, "");
        int len = str.length();
        int courPos;

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            builder.append(str.charAt(i));
            if (i == 3 || i == 7 || i == 11 || i == 15) {
                if (i != len - 1)
                    builder.append(space);
            }
        }
        courPos = builder.length();
        bandCardEdit.setText(builder.toString());
        bandCardEdit.setSelection(courPos);

    }


    private void isILoginGo() {
        String strphone = getText(phone);
        String strname = getText(name);
        String straccountName = getText(accountName);
        String strcode = getText(code);
        String straccountNo = getText(accountNo);
        if (TextUtils.isEmpty(strphone) || TextUtils.isEmpty(strname)
                || TextUtils.isEmpty(straccountName)|| TextUtils.isEmpty(strcode) ||TextUtils.isEmpty(straccountNo)) {
            if (nextBtn!=null&&nextBtn.isEnabled()) {
                nextBtn.setAlpha(0.5f);
                nextBtn.setEnabled(false);
            }

        } else if (nextBtn!=null&&!nextBtn.isEnabled()) {
            nextBtn.setAlpha(1f);
            nextBtn.setEnabled(true);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.btn_verify, R.id.next_btn, R.id.back_btn, accountName_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_verify:
                String strphonecode = getText(phone);
                if (!RegularUtils.isMobileSimple(strphonecode)) {
                    T.show("请输入正确手机号");
                    return;
                }
                mvpPresenter.verifyBank(strphonecode);
                break;
            case R.id.next_btn:
                addBank();
                break;
            case R.id.back_btn:
                finish();
                break;
            case accountName_layout:

            if (CheckUtils.isEmpty(mBlankTableBean)){
                mvpPresenter.bankTabel();
            }else{
               showBlankDialog();
            }


                break;
        }
    }


    private OptionsPickerView.OnOptionsSelectListener mOnOptionsSelectListener = new OptionsPickerView.OnOptionsSelectListener() {




        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            BlankTableBean mItem = mBlankTableBean.get(options1);
            bankCode=mItem.getVal();
            accountName.setText(mItem.getPickerViewText());


        }
    };
    private void addBank() {
        strphone = getText(phone);
        strname = getText(name);
        straccountName = getText(accountName);
        strcode = getText(code);
        straccountNo = getBankCardText();
        if (TextUtils.isEmpty(straccountNo)&&straccountNo.length()<12) {

            T.show("请输入正确银行卡号");
            return ;
        }
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("phone", strphone);
        mHashMap.put("name", strname);
        mHashMap.put("bankCode", bankCode);
        mHashMap.put("verifyCode", strcode);
        mHashMap.put("accountNo", straccountNo);
        mHashMap.put("accessToken", SaveParams.getToken());
       mvpPresenter.addBankCard(mHashMap);
    }


    @Override
    public void verifyBankSucceed() {
        mCountDownUtils.start();
    }

    @Override
    public void addBankCardSucceed() {
        Bundle mBundle = new Bundle();
        mBundle.putString(Constant.ARG_PARAM1, straccountName);
        setFragmentResult(RESULT_OK, mBundle);
        finish();
    }

    @Override
    public void bankTabelSucceed(List<BlankTableBean> mBlankTableBean) {
        this.mBlankTableBean=mBlankTableBean;
        showBlankDialog();

    }
    private void showBlankDialog() {
        KeyBoardUtil.hideKeyboard(_mActivity);
        if (CheckUtils.isNull(mBalankDialog)) {
            mBalankDialog= PickerViewDialog.getInstance().ShowCityPickerView(_mActivity, "", mOnOptionsSelectListener);
            mBalankDialog.setPicker(mBlankTableBean);
            mBalankDialog.show(accountNameLayout);
        } else {

            mBalankDialog.show(accountNameLayout);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mCountDownUtils.cancels();
    }
}
